package com.wgts.wgts.mvp.view.activity.search;

import android.content.Context;
import android.support.annotation.NonNull;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spanned;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.wgts.wgts.R;

import java.util.List;

/**
 * 搜索结果列表界面
 */
public class SearchResultAdatper extends RecyclerView.Adapter<SearchResultAdatper.SearchResultViewHolder> {


    private List<String> srcData;

    private Context context;

    private OnItemClick onItemClick;

    private String mKeyWord;

    public SearchResultAdatper(List<String> srcData, Context context, String mKeyWord) {
        this.srcData = srcData;
        this.context = context;
        this.mKeyWord = mKeyWord;
    }

    public void setOnItemClick(OnItemClick onItemClick){
        this.onItemClick = onItemClick;
    }



    @NonNull
    @Override
    public SearchResultViewHolder onCreateViewHolder(@NonNull ViewGroup viewGroup, int i) {
        return new SearchResultViewHolder(LayoutInflater.from(context).inflate(R.layout.search_result_item, viewGroup, false));
    }

    @Override
    public void onBindViewHolder(@NonNull SearchResultViewHolder searchResultViewHolder, final int i) {

        if(srcData.get(i) != null){
            if (srcData.get(i).contains(mKeyWord)) {
                int index = srcData.get(i).indexOf(mKeyWord);
                int len = mKeyWord.length();
                Spanned temp = Html.fromHtml(srcData.get(i).substring(0, index)
                        + "<font color=#666666>"
                        + srcData.get(i).substring(index, index + len) + "</font>"
                        + "<font color=#000000>" + srcData.get(i).substring(index + len, srcData.get(i).length()) + "</font>");

                searchResultViewHolder.tvSearchResult.setText(temp);
            } else {
                searchResultViewHolder.tvSearchResult.setText(srcData.get(i));
            }
        }
        searchResultViewHolder.itemView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(onItemClick != null){
                    onItemClick.onclick(v, i);
                }
            }
        });
    }

    @Override
    public int getItemCount() {
        return srcData.size();
    }

    public class SearchResultViewHolder extends RecyclerView.ViewHolder {
        public TextView tvSearchResult;
        public View itemView;
        public SearchResultViewHolder(@NonNull View itemView) {
            super(itemView);
            this.itemView = itemView;
            tvSearchResult = itemView.findViewById(R.id.tv_search_result);
        }
    }

    public interface OnItemClick{
        void onclick(View view, int ponstion);
    }
}
